import org.springframework.beans.factory.BeanFactoryAware
import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.BeansException

class ExtractService implements BeanFactoryAware {

    boolean transactional = true

    def taskExecutor
    def beanFactory
    def fetchService

    void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory
    }

    def processSync(String url) {
        fetchService.fetch(url)
    }

    def extractEntry(htmlNode) {
        def type = cmsType(htmlNode)
        def result = extractMap[type](htmlNode)
        return result
    }

    def cmsType(content) {
        def nodes = content.depthFirst().grep { it.'@name' == 'generator' && it.name() == 'META'}
        if (nodes) {
            return nodes[0].'@content'
        }
        return 'unknown'
    }

    def extractMap = [
        'exteen.com' : { html -> 
            def content = html.breadthFirst().grep { it.'@id' == 'content' }[0]

            def title = HtmlUtils.extractText(content.depthFirst().grep { it.name() == 'A' }[0])

            def body = content.breadthFirst().grep { it.'@class' == 'post' }[0]       
            def bodyText = HtmlUtils.extractText(body)

            def tagNodes = content.breadthFirst().grep { it.'@class' == 'tag' }[0]
            def tags = HtmlUtils.extractText(tagNodes).split(',')
            tags[0] = tags[0].replaceAll("^Tags:", '')
            tags =  tags.collect { it.trim() }

            [title: title, body: bodyText, tags: tags]
        },
        'blogger' : { html ->
            def content = html.breadthFirst().grep { it.'@class' =~ /^blog-posts/ }[0]
            def title = HtmlUtils.extractText(content.depthFirst().grep { it.'@class' =~ /^post-title/ }[0].A[0])
        
            def body = content.breadthFirst().grep { it.'@class' =~ /post-body/ }[0]
            def bodyText = HtmlUtils.extractText(body)

            def tagNodes = content.breadthFirst().grep { it.'@rel' == 'tag' }
            def tags = tagNodes.collect { it.value().text() }
            
            [title: title, body: bodyText, tags: tags]
        },
        'WordPress.com' : { html ->
            def content = html.breadthFirst().grep { it.'@class' =~ /post/ && it.'@id' =~ /^post/ }[0]
            def bodyText = HtmlUtils.extractText(content)

            def titleNode = content.depthFirst().grep {it.name() =~ '^H'}[0]
            def title = HtmlUtils.extractText(titleNode)
            
            def tagNodes = html.BODY[0].breadthFirst().grep { it.'@href' =~ /http:\/\/wordpress.com\/tag/ }

            def tags = tagNodes.collect { it.value().text() }        
            [title: title, body: bodyText, tags: tags]
        },
        'unknown' : { html ->
            [title: 'unknown', body: '-', tags: []]
        }
        ]
}
